import { useState, useRef } from 'react';

type StorageType = 'localStorage' | 'sessionStorage';

function useStorageState<T>(key: string, initialState: T, storageType: StorageType = 'localStorage') {
  const [state, setState] = useState<T>(() => {
    try {
      const storedValue = window[storageType].getItem(key);
      return storedValue ? JSON.parse(storedValue) : initialState;
    } catch (error) {
      console.error('Error reading from storage:', error);
      return initialState;
    }
  });

  const stateRef = useRef(state);

  const saveState = () => {
    try {
      window[storageType].setItem(key, JSON.stringify(stateRef.current));
    } catch (error) {
      console.error('Error saving to storage:', error);
    }
  };

  const updateState = (newState: T) => {
    stateRef.current = newState;
    setState(stateRef.current);

    saveState();
  };

  return [state, updateState, stateRef] as const;
}

export default useStorageState;
